<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="css/index.min.css">
    <script src="js/jQuery3.6.0min.js"></script>
    <script src="js/template-native.js"></script>
    <script src="js/index.js"></script>
    <script id="tem" type="text/html">
        <% for(var i = 0 ; i < comments.length ; i++){ %>
            <li uid="<%= comments[i].id %>">
                <p class="flo"><%= comments[i].id %>楼<a href="javascript:;" class="delete">删除</a></p>
                <p class="author">层主：<%= comments[i].username %></p>
                <p class="txt"><%= comments[i].content %></p>
            </li>
       <% } %>
       
    </script>
</head>
<body>
    <div class="main">
        <div class="post">
            <h2>新年快乐</h2>
            <p class="author">楼主：行痴</p>
            <p class="content">新的一年，祝大家新年快乐，身体健康，升职加薪！</p>
        </div>
        <div class="apply">
            <h4>发表回复</h4>
            <label>用户名：</label><input type="text" class="txt">
            <textarea  id="ly" cols="105" rows="5"></textarea>
            <input type="button" value="发表" class="btn">
        </div>
        <div class="floor">
            <ul class="list">
               
            </ul>
        </div>
    </div>
   <script>
        // 获取留言板数据
 var uls = $(".main .floor .list");
 $.ajax({
     url:"http://localhost:3000/db",
     type:"GET",
     success:function(data){
         uls.html(template("tem",data));
        
         deleteURL();
     }
 })
 // 点击发表按钮添加数据
 var txt = $(".main .apply .txt");
 var ly = $(".main .apply #ly");
 var btn = $(".main .apply .btn");

 btn.click(function(){
     var user = txt.val();
     var content = ly.val();
     $.ajax({
         url:"http://localhost:3000/comments",
         type:"POST",
         dataType:"json",
         data:{
             "username": user,
             "content": content
         },
         success:function(data){
             console.log(data);
             uls.append(template("tem",{"comments":[data]}))
             deleteURL();
         }
     });
     // 清空输入
     txt.val("");
     ly.val("");
 });

 // 定义一个点击按钮删除的函数 
 function deleteURL(){
     // 删除数据
     console.log($(".floor .list .delete"));
     $(".floor .list .delete").click(function(){
         lis = $(this).parents("li");
         var index = lis.attr("uid");
         console.log("http://localhost:3000/comments/" + index);
         $.ajax({
             url:"http://localhost:3000/comments/" + index,
             type:"DELETE"
         });
         lis.remove();
     });
 }
   </script>
</body>
</html>